﻿#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <gtk/gtk.h>

#define MAX_STUDENTS 200          
#define MAX_NAME_LENGTH 50        
#define MAX_COURSE_NAME 30        
#define MAX_FILE_NAME 100         
#define MAX_COURSES 10            
#define MAX_CLASS_NAME 30         

// 学生基本信息结构体
typedef struct {
    char name[MAX_NAME_LENGTH];
    int id;
    char class[MAX_CLASS_NAME];
    char gender[10];
} StudentInfo;

// 学生成绩结构体
typedef struct {
    int id;
    float scores[MAX_COURSES];
    char courseNames[MAX_COURSES][MAX_COURSE_NAME];
    int courseCount;
    float average;
} StudentScore;

// 报告配置结构体
typedef struct {
    char title[MAX_NAME_LENGTH];
    char date[20];
    char description[200];
    char class[MAX_CLASS_NAME];
} ReportConfig;

// 统计结果结构体
typedef struct {
    float classAverage;
    float highestScore;
    float lowestScore;
    int passCount;
    int totalCount;
} ReportStatistics;

// 全局数据
static StudentInfo allStudents[MAX_STUDENTS];
static StudentScore allScores[MAX_STUDENTS];
static int studentCount = 0;

bool loadDataFromFile(const char* filename) {
    FILE* file = fopen(filename, "r");
    if (!file) {
        printf("无法打开数据文件: %s\n", filename);
        return false;
    }

    // 读取文件内容并填充到 allStudents 和 allScores 数组中
    // 这里需要根据文件格式编写具体的读取逻辑

    fclose(file);
    return true;
}

// 计算学生平均分
void calculateStudentAverage(StudentScore* score) {
    float sum = 0;
    for (int i = 0; i < score->courseCount; i++) {
        sum += score->scores[i];
    }
    score->average = score->courseCount > 0 ? sum / score->courseCount : 0;
}

// 计算班级统计指标
void calculateClassStatistics(StudentScore scores[], int count, ReportStatistics* stats) {
    if (count == 0) return;

    float sum = 0;
    stats->highestScore = scores[0].average;
    stats->lowestScore = scores[0].average;
    stats->passCount = 0;
    stats->totalCount = count;

    for (int i = 0; i < count; i++) {
        sum += scores[i].average;
        if (scores[i].average > stats->highestScore) stats->highestScore = scores[i].average;
        if (scores[i].average < stats->lowestScore) stats->lowestScore = scores[i].average;
        if (scores[i].average >= 60) stats->passCount++;
    }
    stats->classAverage = sum / count;
}

// 生成单个学生报告（文本格式）
char* generateStudentReport(StudentInfo* info, StudentScore* score, ReportConfig* config) {
    int bufferSize = 2048;
    char* report = (char*)malloc(bufferSize);
    if (!report) {
        printf("内存分配失败！\n");
        return NULL;
    }

    // 生成日期
    time_t now = time(NULL);
    struct tm* t = localtime(&now);
    strftime(config->date, sizeof(config->date), "%Y-%m-%d", t);

    // 填充报告内容
    sprintf(report, "====================== %s ======================\n", config->title);
    sprintf(report + strlen(report), "生成日期：%s\n", config->date);
    sprintf(report + strlen(report), "班级：%s\n", config->class);
    sprintf(report + strlen(report), "描述：%s\n\n", config->description);
    sprintf(report + strlen(report), "学生基本信息：\n");
    sprintf(report + strlen(report), "姓名：%s | 学号：%d | 班级：%s | 性别：%s\n\n",
        info->name, info->id, info->class, info->gender);
    sprintf(report + strlen(report), "===================== 成绩详情 =====================\n");
    sprintf(report + strlen(report), "课程名称\t\t成绩\n");
    sprintf(report + strlen(report), "---------------------------------------\n");

    // 填充课程成绩
    calculateStudentAverage(score);
    for (int i = 0; i < score->courseCount; i++) {
        sprintf(report + strlen(report), "%-20s\t%.2f\n",
            score->courseNames[i], score->scores[i]);
    }

    // 填充平均分
    sprintf(report + strlen(report), "---------------------------------------\n");
    sprintf(report + strlen(report), "平均分：%.2f\n", score->average);
    sprintf(report + strlen(report), "===================== 报告结束 =====================\n");

    return report;
}

// 生成班级汇总报告（文本格式）
char* generateClassReport(StudentInfo info[], StudentScore score[], int count, ReportConfig* config) {
    int bufferSize = 1024 * count;
    char* report = (char*)malloc(bufferSize);
    if (!report) {
        printf("内存分配失败！\n");
        return NULL;
    }

    // 生成日期与报告头部
    time_t now = time(NULL);
    struct tm* t = localtime(&now);
    strftime(config->date, sizeof(config->date), "%Y-%m-%d", t);

    sprintf(report, "====================== %s ======================\n", config->title);
    sprintf(report + strlen(report), "生成日期：%s\n", config->date);
    sprintf(report + strlen(report), "班级：%s\n", config->class);
    sprintf(report + strlen(report), "描述：%s\n\n", config->description);
    sprintf(report + strlen(report), "===================== 班级成绩汇总 =====================\n");
    sprintf(report + strlen(report), "学号\t姓名\t\t平均分\t班级排名\n");
    sprintf(report + strlen(report), "---------------------------------------------------\n");

    // 按平均分排序（降序）
    StudentScore sortedScores[MAX_STUDENTS];
    memcpy(sortedScores, score, sizeof(StudentScore) * count);
    for (int i = 0; i < count - 1; i++) {
        for (int j = 0; j < count - i - 1; j++) {
            if (sortedScores[j].average < sortedScores[j + 1].average) {
                StudentScore temp = sortedScores[j];
                sortedScores[j] = sortedScores[j + 1];
                sortedScores[j + 1] = temp;
            }
        }
    }

    // 填充学生成绩列表与班级统计
    ReportStatistics stats;
    calculateClassStatistics(sortedScores, count, &stats);
    for (int i = 0; i < count; i++) {
        // 查找学生姓名
        char name[MAX_NAME_LENGTH] = "未知";
        for (int j = 0; j < count; j++) {
            if (info[j].id == sortedScores[i].id) {
                strcpy(name, info[j].name);
                break;
            }
        }
        sprintf(report + strlen(report), "%d\t%-15s\t%.2f\t%d\n",
            sortedScores[i].id, name, sortedScores[i].average, i + 1);
    }

    // 填充班级统计
    sprintf(report + strlen(report), "---------------------------------------------------\n");
    sprintf(report + strlen(report), "班级平均分：%.2f | 最高分：%.2f | 最低分：%.2f\n",
        stats.classAverage, stats.highestScore, stats.lowestScore);
    sprintf(report + strlen(report), "及格率：%.2f%%（%d/%d）\n",
        (float)stats.passCount / stats.totalCount * 100,
        stats.passCount, stats.totalCount);
    sprintf(report + strlen(report), "===================== 报告结束 =====================\n");

    return report;
}

// 导出单个学生报告为TXT
bool exportStudentReportToTxt(StudentInfo* info, StudentScore* score,
    ReportConfig* config, const char* fileName) {
    char* report = generateStudentReport(info, score, config);
    if (!report) return false;

    FILE* file = fopen(fileName, "w");
    if (!file) {
        free(report);
        printf("错误：无法创建TXT文件 %s\n", fileName);
        return false;
    }

    fputs(report, file);
    fclose(file);
    free(report);
    return true;
}

// 导出单个学生报告为CSV
bool exportStudentReportToCsv(StudentInfo* info, StudentScore* score, const char* fileName) {
    calculateStudentAverage(score);

    FILE* file = fopen(fileName, "w");
    if (!file) {
        printf("错误：无法创建CSV文件 %s\n", fileName);
        return false;
    }

    // 写入表头与数据
    fprintf(file, "学号,姓名,班级,性别,");
    for (int i = 0; i < score->courseCount; i++) {
        fprintf(file, "%s,", score->courseNames[i]);
    }
    fprintf(file, "平均分\n");

    fprintf(file, "%d,%s,%s,%s,", info->id, info->name, info->class, info->gender);
    for (int i = 0; i < score->courseCount; i++) {
        fprintf(file, "%.2f,", score->scores[i]);
    }
    fprintf(file, "%.2f\n", score->average);

    fclose(file);
    return true;
}

// 导出班级报告为TXT
bool exportClassReportToTxt(StudentInfo info[], StudentScore score[],
    int count, ReportConfig* config, const char* fileName) {
    char* report = generateClassReport(info, score, count, config);
    if (!report) return false;

    FILE* file = fopen(fileName, "w");
    if (!file) {
        free(report);
        printf("错误：无法创建TXT文件 %s\n", fileName);
        return false;
    }

    fputs(report, file);
    fclose(file);
    free(report);
    return true;
}

// 导出班级报告为CSV
bool exportClassReportToCsv(StudentInfo info[], StudentScore score[],
    int count, ReportConfig* config, const char* fileName) {
    if (count == 0) {
        printf("错误：学生数据为空，无法导出\n");
        return false;
    }

    FILE* file = fopen(fileName, "w");
    if (!file) {
        printf("错误：无法创建CSV文件 %s\n", fileName);
        return false;
    }

    // 写入报告元信息
    time_t now = time(NULL);
    struct tm* t = localtime(&now);
    strftime(config->date, sizeof(config->date), "%Y-%m-%d", t);
    fprintf(file, "报告标题,%s\n", config->title);
    fprintf(file, "生成日期,%s\n", config->date);
    fprintf(file, "班级,%s\n", config->class);
    fprintf(file, "描述,%s\n\n", config->description);

    // 写入表头
    fprintf(file, "学号,姓名,班级,性别,");
    for (int i = 0; i < score[0].courseCount; i++) {
        fprintf(file, "%s,", score[0].courseNames[i]);
    }
    fprintf(file, "平均分\n");

    // 写入学生数据
    for (int i = 0; i < count; i++) {
        calculateStudentAverage(&score[i]);
        char name[MAX_NAME_LENGTH] = "未知", gender[MAX_NAME_LENGTH] = "未知", className[MAX_CLASS_NAME] = "未知";
        for (int j = 0; j < count; j++) {
            if (info[j].id == score[i].id) {
                strcpy(name, info[j].name);
                strcpy(gender, info[j].gender);
                strcpy(className, info[j].class);
                break;
            }
        }
        fprintf(file, "%d,%s,%s,%s,", score[i].id, name, className, gender);
        for (int j = 0; j < score[i].courseCount; j++) {
            fprintf(file, "%.2f,", score[i].scores[j]);
        }
        fprintf(file, "%.2f\n", score[i].average);
    }

    // 写入班级统计
    ReportStatistics stats;
    calculateClassStatistics(score, count, &stats);
    fprintf(file, "\n班级平均分,%.2f,最高分,%.2f,最低分,%.2f,及格率,%.2f%%\n",
        stats.classAverage, stats.highestScore, stats.lowestScore,
        (float)stats.passCount / stats.totalCount * 100);

    fclose(file);
    return true;
}

// 查找学生信息
bool fetchStudentInfoById(int studentId, StudentInfo* targetInfo, StudentScore* targetScore) {
    for (int i = 0; i < studentCount; i++) {
        if (allStudents[i].id == studentId) {
            *targetInfo = allStudents[i];
            *targetScore = allScores[i];
            return true;
        }
    }
    return false;
}

// 查找班级学生
int fetchClassStudents(const char* className, StudentInfo** classInfo, StudentScore** classScore) {
    int count = 0;
    for (int i = 0; i < studentCount; i++) {
        if (strcmp(allStudents[i].class, className) == 0) {
            count++;
        }
    }

    if (count == 0) return 0;

    *classInfo = (StudentInfo*)malloc(count * sizeof(StudentInfo));
    *classScore = (StudentScore*)malloc(count * sizeof(StudentScore));
    if (!*classInfo || !*classScore) {
        if (*classInfo) free(*classInfo);
        if (*classScore) free(*classScore);
        return 0;
    }

    int index = 0;
    for (int i = 0; i < studentCount; i++) {
        if (strcmp(allStudents[i].class, className) == 0) {
            (*classInfo)[index] = allStudents[i];
            (*classScore)[index] = allScores[i];
            index++;
        }
    }

    return count;
}

// 显示消息对话框
void show_message_dialog(GtkWindow* parent, const char* title, const char* message, GtkMessageType type) {
    GtkWidget* dialog = gtk_message_dialog_new(
        parent,
        GTK_DIALOG_DESTROY_WITH_PARENT,
        type,
        GTK_BUTTONS_OK,
        "%s", message
    );
    gtk_window_set_title(GTK_WINDOW(dialog), title);
    gtk_dialog_run(GTK_DIALOG(dialog));
    gtk_widget_destroy(dialog);
}

// 学生报告对话框回调
static void on_generate_student_report(GtkWidget* widget, gpointer data) {
    GtkWidget* dialog = GTK_WIDGET(data);
    GtkWidget* entry = gtk_builder_get_object(GTK_BUILDER(data), "student_id_entry");
    const char* id_text = gtk_entry_get_text(GTK_ENTRY(entry));
    int studentId = atoi(id_text);

    if (studentId <= 0) {
        show_message_dialog(GTK_WINDOW(dialog), "输入错误", "请输入有效的学号", GTK_MESSAGE_ERROR);
        return;
    }

    StudentInfo targetInfo = { 0 };
    StudentScore targetScore = { 0 };
    bool dataFound = fetchStudentInfoById(studentId, &targetInfo, &targetScore);

    if (!dataFound) {
        show_message_dialog(GTK_WINDOW(dialog), "未找到数据", "未找到该学号的学生数据", GTK_MESSAGE_INFO);
        return;
    }

    // 创建格式选择对话框
    GtkWidget* format_dialog = gtk_dialog_new_with_buttons(
        "选择导出格式",
        GTK_WINDOW(dialog),
        GTK_DIALOG_DESTROY_WITH_PARENT,
        "TXT", GTK_RESPONSE_OK,
        "CSV", GTK_RESPONSE_CANCEL,
        NULL
    );
    gtk_window_set_default_size(GTK_WINDOW(format_dialog), 300, 200);

    int response = gtk_dialog_run(GTK_DIALOG(format_dialog));
    gtk_widget_destroy(format_dialog);

    // 设置报告配置
    ReportConfig config = {
        .title = "学生成绩报告",
        .description = "自动生成的成绩统计报告"
    };
    char title[MAX_NAME_LENGTH];
    if (strlen(targetInfo.name) > 0) {
        sprintf(title, "%s-%d-%s", config.title, targetInfo.id, targetInfo.name);
    }
    else {
        sprintf(title, "%s-学号%d", config.title, targetInfo.id);
    }
    strcpy(config.title, title);
    strcpy(config.class, targetInfo.class);

    // 创建文件选择对话框
    GtkWidget* file_chooser = gtk_file_chooser_dialog_new(
        "保存报告",
        GTK_WINDOW(dialog),
        GTK_FILE_CHOOSER_ACTION_SAVE,
        "取消", GTK_RESPONSE_CANCEL,
        "保存", GTK_RESPONSE_ACCEPT,
        NULL
    );

    char default_filename[MAX_FILE_NAME];
    if (response == GTK_RESPONSE_OK) {
        sprintf(default_filename, "%s.txt", title);
        gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(file_chooser), default_filename);
    }
    else {
        sprintf(default_filename, "%s.csv", title);
        gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(file_chooser), default_filename);
    }

    gint result = gtk_dialog_run(GTK_DIALOG(file_chooser));
    if (result == GTK_RESPONSE_ACCEPT) {
        char* filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(file_chooser));
        bool export_result = false;

        if (response == GTK_RESPONSE_OK) {
            export_result = exportStudentReportToTxt(&targetInfo, &targetScore, &config, filename);
        }
        else {
            export_result = exportStudentReportToCsv(&targetInfo, &targetScore, filename);
        }

        if (export_result) {
            char message[200];
            sprintf(message, "报告已成功导出至:\n%s", filename);
            show_message_dialog(GTK_WINDOW(dialog), "导出成功", message, GTK_MESSAGE_INFO);
        }
        else {
            show_message_dialog(GTK_WINDOW(dialog), "导出失败", "导出报告时发生错误", GTK_MESSAGE_ERROR);
        }

        g_free(filename);
    }

    gtk_widget_destroy(file_chooser);
    gtk_widget_destroy(dialog);
}

// 班级报告对话框回调
static void on_generate_class_report(GtkWidget* widget, gpointer data) {
    GtkWidget* dialog = GTK_WIDGET(data);
    GtkWidget* entry = gtk_builder_get_object(GTK_BUILDER(data), "class_name_entry");
    const char* class_name = gtk_entry_get_text(GTK_ENTRY(entry));

    if (strlen(class_name) == 0) {
        show_message_dialog(GTK_WINDOW(dialog), "输入错误", "请输入班级名称", GTK_MESSAGE_ERROR);
        return;
    }

    StudentInfo* classInfo = NULL;
    StudentScore* classScore = NULL;
    int classCount = fetchClassStudents(class_name, &classInfo, &classScore);

    if (classCount == 0) {
        show_message_dialog(GTK_WINDOW(dialog), "未找到数据", "未找到该班级的学生数据", GTK_MESSAGE_INFO);
        return;
    }

    // 创建格式选择对话框
    GtkWidget* format_dialog = gtk_dialog_new_with_buttons(
        "选择导出格式",
        GTK_WINDOW(dialog),
        GTK_DIALOG_DESTROY_WITH_PARENT,
        "TXT", GTK_RESPONSE_OK,
        "CSV", GTK_RESPONSE_CANCEL,
        NULL
    );
    gtk_window_set_default_size(GTK_WINDOW(format_dialog), 300, 200);

    int response = gtk_dialog_run(GTK_DIALOG(format_dialog));
    gtk_widget_destroy(format_dialog);

    // 设置报告配置
    ReportConfig config = {
        .title = "班级成绩汇总报告",
        .description = "自动生成的班级成绩统计报告"
    };
    char title[MAX_NAME_LENGTH];
    sprintf(title, "%s-%s", config.title, class_name);
    strcpy(config.title, title);
    strcpy(config.class, class_name);

    // 创建文件选择对话框
    GtkWidget* file_chooser = gtk_file_chooser_dialog_new(
        "保存报告",
        GTK_WINDOW(dialog),
        GTK_FILE_CHOOSER_ACTION_SAVE,
        "取消", GTK_RESPONSE_CANCEL,
        "保存", GTK_RESPONSE_ACCEPT,
        NULL
    );

    char default_filename[MAX_FILE_NAME];
    if (response == GTK_RESPONSE_OK) {
        sprintf(default_filename, "%s.txt", title);
        gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(file_chooser), default_filename);
    }
    else {
        sprintf(default_filename, "%s.csv", title);
        gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(file_chooser), default_filename);
    }

    gint result = gtk_dialog_run(GTK_DIALOG(file_chooser));
    if (result == GTK_RESPONSE_ACCEPT) {
        char* filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(file_chooser));
        bool export_result = false;

        if (response == GTK_RESPONSE_OK) {
            export_result = exportClassReportToTxt(classInfo, classScore, classCount, &config, filename);
        }
        else {
            export_result = exportClassReportToCsv(classInfo, classScore, classCount, &config, filename);
        }

        if (export_result) {
            char message[200];
            sprintf(message, "报告已成功导出至:\n%s", filename);
            show_message_dialog(GTK_WINDOW(dialog), "导出成功", message, GTK_MESSAGE_INFO);
        }
        else {
            show_message_dialog(GTK_WINDOW(dialog), "导出失败", "导出报告时发生错误", GTK_MESSAGE_ERROR);
        }

        g_free(filename);
    }

    // 释放内存
    if (classInfo) free(classInfo);
    if (classScore) free(classScore);

    gtk_widget_destroy(dialog);
}

// 显示学生报告对话框
static void show_student_report_dialog(GtkWidget* widget, gpointer data) {
    GtkBuilder* builder = gtk_builder_new_from_string(
        "<interface>"
        "  <object class=\"GtkDialog\" id=\"student_dialog\">"
        "    <property name=\"title\">生成学生报告</property>"
        "    <property name=\"default-width\">400</property>"
        "    <property name=\"default-height\">200</property>"
        "    <property name=\"modal\">true</property>"
        "    <child internal-child=\"vbox\">"
        "      <object class=\"GtkBox\">"
        "        <property name=\"margin\">10</property>"
        "        <property name=\"spacing\">10</property>"
        "        <child>"
        "          <object class=\"GtkLabel\">"
        "            <property name=\"label\">请输入学生学号:</property>"
        "            <property name=\"halign\">GTK_ALIGN_START</property>"
        "          </object>"
        "        </child>"
        "        <child>"
        "          <object class=\"GtkEntry\" id=\"student_id_entry\">"
        "            <property name=\"max-length\">10</property>"
        "            <property name=\"input-purpose\">GTK_INPUT_PURPOSE_DIGITS</property>"
        "          </object>"
        "        </child>"
        "      </object>"
        "    </child>"
        "    <child internal-child=\"action_area\">"
        "      <object class=\"GtkButtonBox\">"
        "        <child>"
        "          <object class=\"GtkButton\">"
        "            <property name=\"label\">取消</property>"
        "            <signal name=\"clicked\" handler=\"gtk_widget_destroy\"/>"
        "          </object>"
        "        </child>"
        "        <child>"
        "          <object class=\"GtkButton\">"
        "            <property name=\"label\">生成报告</property>"
        "            <signal name=\"clicked\" handler=\"on_generate_student_report\" user-data=\"student_dialog\"/>"
        "          </object>"
        "        </child>"
        "      </object>"
        "    </child>"
        "  </object>"
        "</interface>", -1);

    GError* error = NULL;
    gtk_builder_connect_signals(builder, NULL);
    if (error) {
        g_printerr("Error connecting signals: %s\n", error->message);
        g_error_free(error);
    }

    GtkWidget* dialog = GTK_WIDGET(gtk_builder_get_object(builder, "student_dialog"));
    gtk_window_set_transient_for(GTK_WINDOW(dialog), GTK_WINDOW(data));
    gtk_widget_show_all(dialog);

    g_object_unref(builder);
}

// 显示班级报告对话框
static void show_class_report_dialog(GtkWidget* widget, gpointer data) {
    GtkBuilder* builder = gtk_builder_new_from_string(
        "<interface>"
        "  <object class=\"GtkDialog\" id=\"class_dialog\">"
        "    <property name=\"title\">生成班级报告</property>"
        "    <property name=\"default-width\">400</property>"
        "    <property name=\"default-height\">200</property>"
        "    <property name=\"modal\">true</property>"
        "    <child internal-child=\"vbox\">"
        "      <object class=\"GtkBox\">"
        "        <property name=\"margin\">10</property>"
        "        <property name=\"spacing\">10</property>"
        "        <child>"
        "          <object class=\"GtkLabel\">"
        "            <property name=\"label\">请输入班级名称:</property>"
        "            <property name=\"halign\">GTK_ALIGN_START</property>"
        "          </object>"
        "        </child>"
        "        <child>"
        "          <object class=\"GtkEntry\" id=\"class_name_entry\">"
        "            <property name=\"max-length\">50</property>"
        "          </object>"
        "        </child>"
        "      </object>"
        "    </child>"
        "    <child internal-child=\"action_area\">"
        "      <object class=\"GtkButtonBox\">"
        "        <child>"
        "          <object class=\"GtkButton\">"
        "            <property name=\"label\">取消</property>"
        "            <signal name=\"clicked\" handler=\"gtk_widget_destroy\"/>"
        "          </object>"
        "        </child>"
        "        <child>"
        "          <object class=\"GtkButton\">"
        "            <property name=\"label\">生成报告</property>"
        "            <signal name=\"clicked\" handler=\"on_generate_class_report\" user-data=\"class_dialog\"/>"
        "          </object>"
        "        </child>"
        "      </object>"
        "    </child>"
        "  </object>"
        "</interface>", -1);

    GError* error = NULL;
    gtk_builder_connect_signals(builder, NULL);
    if (error) {
        g_printerr("Error connecting signals: %s\n", error->message);
        g_error_free(error);
    }

    GtkWidget* dialog = GTK_WIDGET(gtk_builder_get_object(builder, "class_dialog"));
    gtk_window_set_transient_for(GTK_WINDOW(dialog), GTK_WINDOW(data));
    gtk_widget_show_all(dialog);

    g_object_unref(builder);
}

// 主函数
int main(int argc, char* argv[]) {
    // 初始化GTK
    gtk_init(&argc, &argv);

    if (!loadDataFromFile("students.dat")) {
        printf("加载数据失败，请检查数据文件\n");
        return 1;
    }

    // 创建主窗口
    GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(GTK_WINDOW(window), "学生成绩报告生成系统");
    gtk_window_set_default_size(GTK_WINDOW(window), 600, 400);
    g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);

    // 创建主布局
    GtkWidget* vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 20);
    gtk_container_add(GTK_CONTAINER(window), vbox);
    gtk_container_set_border_width(GTK_CONTAINER(vbox), 20);

    // 添加标题
    GtkWidget* title = gtk_label_new("<span size=\"x-large\" weight=\"bold\">学生成绩报告生成系统</span>");
    gtk_label_set_use_markup(GTK_LABEL(title), TRUE);
    gtk_box_pack_start(GTK_BOX(vbox), title, FALSE, FALSE, 10);

    // 添加按钮容器
    GtkWidget* button_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 20);
    gtk_box_pack_start(GTK_BOX(vbox), button_box, FALSE, FALSE, 20);
    gtk_box_set_homogeneous(GTK_BOX(button_box), TRUE);

    // 添加学生报告按钮
    GtkWidget* student_button = gtk_button_new_with_label("生成学生报告");
    g_signal_connect(student_button, "clicked", G_CALLBACK(show_student_report_dialog), window);
    gtk_box_pack_start(GTK_BOX(button_box), student_button, TRUE, TRUE, 0);
    gtk_widget_set_size_request(student_button, 200, 80);

    // 添加班级报告按钮
    GtkWidget* class_button = gtk_button_new_with_label("生成班级报告");
    g_signal_connect(class_button, "clicked", G_CALLBACK(show_class_report_dialog), window);
    gtk_box_pack_start(GTK_BOX(button_box), class_button, TRUE, TRUE, 0);
    gtk_widget_set_size_request(class_button, 200, 80);

    // 添加状态栏
    GtkWidget* status_bar = gtk_statusbar_new();
    gtk_box_pack_end(GTK_BOX(vbox), status_bar, FALSE, FALSE, 0);
    gtk_statusbar_push(GTK_STATUSBAR(status_bar),
        gtk_statusbar_get_context_id(GTK_STATUSBAR(status_bar), "status"),
        "就绪");

    // 显示所有控件
    gtk_widget_show_all(window);

    // 开始GTK主循环
    gtk_main();

    return 0;
}